<?php
require_once("lib/db/mysqlDatabase.php");
require_once("lib/inc_configuration.php");

class MailQueue {

	public $mailQueue;

	function __construct(){
		$this->mailQueue = array();
		$this->getMailQueue();
	}
	
	function getMailQueue(){
		$q = "SELECT * FROM mail_queue ORDER BY priority DESC, 
					creation_date DESC LIMIT ".MQ_NUMBER_OF_ROWS_FETCH;
		$query = new mysqlQuery("tournament", $q, "", "", "", "", "");
		$query->execute();
		while($row = $query->next()){
			$mail = new Mail(	$row["id"], 
												$row["subject"], 
												$row["destination"], 
												$row["body"], 
												$row["priority"]);
			array_push($this->mailQueue, $mail);
		}		
	}
	
	function processQueue(){
		$header = "Return-Path: ".MQ_REPLY_MAIL."\n";
		$header .= "X-Sender: ".MQ_REPLY_MAIL."\n";
		$header .= "From: PES6J Tournament <".MQ_REPLY_MAIL.">\n";
		$header .= "X-Mailer: PHP 5.1\n";
		$header .= "MIME-Version: 1.0\n";
		$header .= "Content-type: text/html\n";
		
		ini_set("SMTP", "mail.pes6j.net");
		ini_set("smtp_port", "25");
		ini_set(sendmail_from, MQ_REPLY_MAIL);
				
		foreach($this->mailQueue as $mail){
			$body = "<html><head><title>PES6J Tournament</title></head><body>".nl2br($mail->getBody())."<p><strong>This is an automatic generated e-mail, do not anwser it.</strong></body></html>";
			mail(	$mail->getDestination(), 
						$mail->getSubject(), 
						$body, 
						$header);
			$this->purgeMail($mail);	
		}
	}
	
	function purgeMail($mail){
		$d = "DELETE FROM `mail_queue` WHERE `id` = '".$mail->getId()."'";
		$delete = new mysqlDelete("tournament", $d, "", "");
		$delete->execute();
	}
	
	function enQueue($mail){
		if($mail->getDestination()){
			$values = array(NULL, $mail->getSubject(), $mail->getBody(), $mail->getDestination(), $mail->getPriority);
			$insert = new mysqlInsert("tournament", "", "`mail_queue`", $values);
			$insert->execute();
		}
	}
	
	function createMail($body, $subject, $destination, $priority){
		$mail = new Mail(NULL, $subject, $destination, $body, $priority);	
		$this->enQueue($mail);		
	}
}
?>